using System;
using System.IO;
using System.Xml.Serialization;
using MaxAlarm.Properties;

namespace MaxAlarm.Core.Settings
{
    public class SettingsProvider
    {
        private static readonly string SettingsFile;

        private static readonly MaxAlarmSettings DefaultSettings = new MaxAlarmSettings
                                                                       {
                                                                           AccountsSettings = new AccountsSettings(),
                                                                           AlarmSettings = new AlarmSettings(),
                                                                           AutoRefreshInterval = 10,
                                                                           BaseAddress = "127.0.0.1",
                                                                           StartupFilters = "pol|kh",
                                                                           AlertSettings = new AlertSettings()
                                                                       };

        static SettingsProvider()
        {
            SettingsFile = Path.Combine(Environment.CurrentDirectory, ApplicationConstants.SettingsFile);
        }

        public MaxAlarmSettings GetSettings()
        {
            try
            {
                using (var reader = new StreamReader(SettingsFile))
                {
                    var serializer = new XmlSerializer(typeof (MaxAlarmSettings));
                    return (MaxAlarmSettings)serializer.Deserialize(reader);
                }
            }
            catch
            {
                return DefaultSettings;
            }
        }

        public bool SaveSettings(MaxAlarmSettings settings)
        {
            try
            {
                using (var writer = new StreamWriter(SettingsFile, false))
                {
                    var serializer = new XmlSerializer(typeof(MaxAlarmSettings));
                    serializer.Serialize(writer, settings);
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
    }
}
